<template>
  <div class="scroll-wrapper">
    {{ channel }}
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.art_id" :title="item.title">
          <div slot="label">
            <van-grid
              v-if="item.cover.images"
              :column-num="item.cover.images.length"
            >
              <van-grid-item
                v-for="(imgSrc, idx) in item.cover.images"
                :key="idx"
              >
                <!-- {{imgSrc}} -->
                <van-image :src="imgSrc" lazy-load />
              </van-grid-item>
            </van-grid>

            <!-- 文字区域 -->
            <div class="meta">
              <span>{{ item.aut_name }}</span>
              <span>{{ item.comm_count }}评论</span>
              <span>{{ item.pubdate | relativeTime }}</span>

              <!-- 登录（看有没有token）才能看到这个关闭按钮 -->
              <span
                class="close"
                @click="hMoreAction(item.art_id)"
                v-if="$store.state.list.token"
              >
                <van-popup v-model="isShowMoreAction" :style="{ width: '80%' }">
                  <MoreAction
                    @No_interest="No_interest"
                    @report="hReport"
                  ></MoreAction>
                </van-popup>
                <van-icon name="cross" />
              </span>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import MoreAction from './moreAction.vue'
import { getArticles, disLike, report } from '../../api/acticle.js'
export default {
  name: 'articleList',
  data () {
    return {
      articleId: null,
      isShowMoreAction: false, // 初始不显示弹层
      list: [],
      loading: false,
      refreshing: false,
      finished: false,
      timestamp: Date.now()
    }
  },
  props: ['channel'],
  methods: {
    async hReport (reportTypeId) {
      console.log('收到的举报类型是', reportTypeId)
      try {
        // 1. 发请求,举报
        const res = await report(this.articleId, reportTypeId)
        console.log(res)
        // 2. 删除文章:根据文章的编号在list中删除
        this.delArticle(this.articleId)
        // 3. 关闭弹层
        this.isShowMoreAction = false

        this.$toast.success('操作成功')
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }
    },
    async onRefresh () {
      // Date.now(): 请求新的推荐数据传当前的时间戳
      const res = await getArticles(this.channel.id, Date.now())
      // 获取的数据
      const arr = res.data.data.results // 它是一个数组
      // 1. 追加数据到list的头部
      //    对数组进行展开
      this.list.unshift(...arr)

      // 2. 把loading设置为false
      this.refreshing = false

      this.$toast.success('成功加载数据')
    },
    async onLoad () {
      try {
        // 异步更新数据
        const res = await getArticles(this.channel.id, this.timestamp)
        console.log(res.data.data.pre_timestamp)
        this.timestamp = res.data.data.pre_timestamp
        this.list.push(...res.data.data.results)
        this.loading = false
        if (res.data.data.results.length === 0 || res.data.data.pre_timestamp === null) {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
      }

      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   // this.$store.dispatch('action', payload)
      //   // for (let i = 0; i < 50; i++) {
      //   //   this.list.push(this.list.length + 1)
      //   // }

      //   // 加载状态结束
      //   this.loading = false

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true
      //   }
      // }, 1000)
    },
    hMoreAction (id) {
      this.isShowMoreAction = true
      this.articleId = id
      console.log(this.$refs.refMoreAction)
      if (this.$refs.refMoreAction) {
        this.$refs.refMoreAction.isReport = false
      }
    },
    async No_interest () {
      try {
        await disLike(this.articleId)
        console.log(this.articleId)
        // this.list = this.list.filter(x => x.art_id !== this.articleId)
        this.delArticle(this.articleId)
        this.isShowMoreAction = false
        this.$toast.success('举报成功，感谢您的支持')
      } catch (err) {
        console.log(err)
        this.$toast.fail('举报失败')
      }
    },
    delArticle (articleId) {
      // 1. 找到文章
      const idx = this.list.findIndex(item => {
        if (item.art_id === articleId) {
          return true
        }
      })
      // 2. 删除
      if (idx !== -1) {
        this.list.splice(idx, 1)
      }
    }

  },
  components: {
    MoreAction
  }
}
</script>

<style lang="less" scoped>
.meta {
  span {
    margin-right: 10px;
  }
  display: flex;
  // 让它在最右边
  .close {
    // 它的父级容器是flex的，给当前元素设置左外边距为auto，会让这个元素在父级容器
    // 的最右边
    margin-left: auto;
  }
}
</style>
